package chapter.c5d17;

import java.lang.reflect.Array;
import java.util.Arrays;

public class CopyOfTest {
    public static void main(String[] args) {
        Object[] from0 = {5, 4, 3, 2, 1};
        from0 = badCopyOf(from0, 3);

        System.out.println(Arrays.toString(from0));

        String[] from1 = {"a", "b", "c", "d", "e", "f", "g"};
        from1 = (String[]) goodCopyOf(from1, 5);

        System.out.println(Arrays.toString(from1));
    }

    public static Object[] badCopyOf(Object[] from, int length) {
        Object[] newest = new Object[length];

        System.arraycopy(from, 0, newest, 0, Math.min(length, from.length));

        return newest;
    }

    public static Object goodCopyOf(Object from, int length) {
        Class clz = from.getClass();
        if (!clz.isArray()) return null;

        Class componentType = clz.getComponentType();

        // 生成新的数组
        Object newest = Array.newInstance(componentType, length);
        System.arraycopy(from, 0, newest, 0, Math.min(length, Array.getLength(from)));

        return newest;
    }
}
